#include "factory.h"
//执行对应的命令
int command(train_state_t* ct,Client_State_t* p)
{
    if(ct->cmd_type==CD)
    {
        do_cd(ct,p);
    }
    else if(ct->cmd_type==LS)
    {
        do_ls(ct,p);
    }
    else if(ct->cmd_type==REMOVE)
    {
        do_remove(ct,p);
    }
    else if(ct->cmd_type==PWD)
    {
        do_pwd(p);
    }
}

//执行cd进入对应目录
int do_cd(train_state_t* ct,Client_State_t* p)
{
	int i,j,temp,ret;
    if(ct->file_name=="..")
	{
		bzero(p->path,sizeof(p->path));
		getcwd(p->path,sizeof(p->path));
		for(i=strlen(p->path)-1;i>=0;i++)
		{
			if(p->path[i]=='/')
			{
				p->path[i]=0;
				break;
			}
			p->path[i]=0;
		}
		int len=strlen(p->path);
		ret=send_n(p->new_fd,&len,sizeof(int));
		ERROR_CHECK(ret,-1,"send_n");
		ret=send_n(p->new_fd,p->path,len);
		ERROR_CHECK(ret,-1,"send_n");
	}
	else if(ct->file_name==".")
	{
		bzero(p->path,sizeof(p->path));
		getcwd(p->path,sizeof(p->path));
		int len=strlen(p->path);
		ret=send_n(p->new_fd,&len,sizeof(int));
		ERROR_CHECK(ret,-1,"send_n");
		ret=send_n(p->new_fd,p->path,len);
		ERROR_CHECK(ret,-1,"send_n");
	}
}
//执行ls得到该目录下的文件信息发送给客户端
int do_ls(train_state_t* ct,Client_State_t* p)
{
	int ret;
    DIR* pdir = opendir(ct->file_name);
	if(pdir == NULL)
	{
		int flag = -1 ;
		send(p->new_fd, &flag, sizeof(int), 0);
	}else
	{
		struct dirent* mydir;
        struct stat buf;
		int len ;
		while(mydir=readdir(pdir))//读取目录
		{
			if(strncmp(mydir->d_name, ".", 1) == 0 || strncmp(mydir->d_name,"..", 2) == 0)
			{
				continue;
			}
			bzero(&buf,sizeof(stat));
			stat(mydir->d_name, &buf);//获取某个文件的信息
			bzero(p->path,sizeof(p->path));
			sprintf(p->path,mydir->d_name, buf.st_size);
			len=strlen(p->path);
			ret=send_n(p->new_fd,&len, sizeof(int));//发送数据给客户端
			ERROR_CHECK(ret,-1,"send_n");
			ret=send_n(p->new_fd,p->path, len);
			ERROR_CHECK(ret,-1,"send_n");
		}
		len = 0 ;
		ret=send_n(p->new_fd, &len, sizeof(int));
		ERROR_CHECK(ret,-1,"send_n");
	}
}
//执行rm，满足客户端的请求
int do_remove(train_state_t* ct,Client_State_t* p)
{
	int ret;
    char buf[128]={0};
	sprintf(buf, "rm -rf %s",ct->file_name);
	system(buf);
	bzero(p->path, sizeof(p->path));
	sprintf(p->path, "%s is removed",ct->file_name);
	int len=strlen(p->path);
	ret=send_n(p->new_fd,&len,sizeof(int));
	ERROR_CHECK(ret,-1,"send_n");
	ret=send_n(p->new_fd,p->path,len);
	ERROR_CHECK(ret,-1,"send_n");
}
//通过getcwd拿到当前路径，并发送给客户端
int do_pwd(Client_State_t* p)
{
	int ret;
    bzero(p->path,sizeof(p->path));
    getcwd(p->path,sizeof(p->path));
    int len=strlen(p->path)+1;
    ret=send_n(p->new_fd,&len,sizeof(int));
	ERROR_CHECK(ret,-1,"send_n");
    ret=send_n(p->new_fd,p->path,len);
	ERROR_CHECK(ret,-1,"send_n");
	printf("%s\n",p->path);
}
